package org.web.base.helper;

import org.web.base.domain.exception.ResultMessageEnum;
import org.web.base.domain.exception.ServiceException;
import org.web.base.domain.helper.ServiceExceptionHelper;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 *
 */
public class TelnetHelper {

    /**
     * 测试telnet 机器端口的连通性
     *
     * @param hostname IP或者域名
     * @param port     端口号
     * @param timeout  超时时间
     * @return 是否存在连接
     */
    public static boolean telnet(String hostname, int port, int timeout) throws ServiceException {
        Socket socket = null;
        boolean isConnected;
        try {
            socket = new Socket();
            socket.connect(new InetSocketAddress(hostname, port), timeout); // 建立连接
            isConnected = socket.isConnected(); // 通过现有方法查看连通状态
        } catch (IOException e) {
            throw ServiceExceptionHelper.buildServiceException(e, ResultMessageEnum.OUTER_SYSTEM_EXCEPTION,"Access info is " +hostname + port);
        } finally {
            if (socket != null) {
                try {
                    socket.close();   // 关闭连接
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return isConnected;
    }

}
